import { ref, onMounted, watch } from 'vue';
import { defineStore } from 'pinia';
import { getWeather, getCurWeather } from '@/apis/weather';

export const useCityItemStore = defineStore('CityItem', () => {
  const cityList = ref([]);
  const showCity = ref('');
  const showCityWeather = ref('');
  const setShowCity = (name, adcode) => {
    let weather = '';
    getCurWeather(adcode).then((res) => {
      weather = res.data.lives[0];
      showCity.value = { adcode, name, weather };
    });
    getWeather(adcode).then((res) => {
      showCityWeather.value = res.data.forecasts[0].casts;
    });
  };
  const addCity = () => {
    cityList.value.push(showCity.value);
  };
  const removeCity = (adcode) => {
    cityList.value = cityList.value.filter((item) => item.adcode !== adcode);
  };
  const updateCity = (city) => {
    city.forEach((item) => {
      getCurWeather(item.adcode).then((res) => {
        item.weather = res.data.lives[0];
      });
    });
    cityList.value = city;
  };
  const getCityWeather = (adcode) => {
    getWeather(adcode).then((res) => {
      showCityWeather.value = res.data.forecasts[0].casts;
    });
  };
  watch(
    cityList,
    () => {
      localStorage.setItem('cities', JSON.stringify(cityList.value));
    },
    { deep: true }
  );
  onMounted(() => {
    if (localStorage.getItem('cities')) {
      const cities = JSON.parse(localStorage.getItem('cities'));
      cityList.value = cities;
    }
    updateCity(cityList.value);
  });
  return {
    cityList,
    showCity,
    showCityWeather,
    getCityWeather,
    addCity,
    removeCity,
    setShowCity,
  };
});
